/*
    1. Write a C program to reverse the digits of a given integer.
    Example:
    Input:
    i = 123
    i = 208478933
    i = -73634
    Output:
    Reverse integer: 321
    Reverse integer: 339874802
    Reverse integer: -43637
*/

#include <stdio.h>
#include <stdlib.h>

int getLenOfInteger(int n){
    int num = 1;
    while((n = n / 10)){
        num++;
    }
    return num;
}

int getBitOfInteger(int n, int idx){
    int i = 0;
    while(i++ < idx){
        n = n / 10;
    }
    return n % 10;
}

int reverseInteger(int n){
    int len = getLenOfInteger(n);
    int i, j, bit;
    int ret = 0;;
    for(i = 0; i < len; i++){
        bit = getBitOfInteger(n, i);
        j = len - i - 1;
        while(j--){
            bit = bit * 10;
        }
        ret += bit;
    }
    return ret;
}

int reverseInteger2(int n){
    int len = getLenOfInteger(n);
    int *a = (int *)malloc(len * sizeof(int));
    int i, j, tmp, ret = 0, x = 1;
    for(i = 0; i < len; i++){
        a[i] = getBitOfInteger(n, i);
    }
    i = len - 1;
    while(i >= 0){
        ret += a[i] * x;
        x = x * 10;
        i--;
    }
    free(a);
    return ret;
}

void main(void){
    printf("%d\n", reverseInteger2(12345));
    printf("%d\n", reverseInteger(-12345));
}